<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/7/12
 * Time: 10:05
 */

namespace app\admin\controller;


use app\admin\model\GoodsModel;
use app\admin\validate\GoodsValidate;
use cmf\controller\AdminBaseController;

class GoodsController extends AdminBaseController
{

    public function index()
    {
        $keyword = $this->request->param('keyword');
        $goodsModel = new GoodsModel();

        $where = array('is_del'=>0);
        if (!empty($keyword)){
            $where['goods_name'] = array('like', '%'.$keyword.'%');
            $this->assign('keyword', $keyword);
        }

        $list = $goodsModel->where($where)->paginate(20);
        $page = $list->render();

        return $this->fetch('', array(
            'list' => $list,
            'page' => $page
        ));
    }

    public function edit()
    {
        $id = $this->request->param('id', 0, 'int');
        $goodsModel = new GoodsModel();

        if (!empty($id)){
            $goodsInfo = $goodsModel->find($id);
            $this->assign('goodsInfo', $goodsInfo);
        }

        return $this->fetch();
    }

    public function savePost()
    {
        $data = $this->request->param();
        $goodsModel = new GoodsModel();
        $goodsValidate = new GoodsValidate();

        //数据验证
        if (!$goodsValidate->check($data)){
            $this->error($goodsValidate->getError());
        }

        if (!isset($data['id']) || empty($data['id'])){//添加数据
            //数据保存
            $result = $goodsModel->save(array('goods_name'=>$data['goods_name']));

            if (!$result){
                $this->error('添加失败');
            }

            $this->success('添加成功');
        }else{//修改数据
            //数据保存
            $result = $goodsModel->save(array('goods_name'=>$data['goods_name']), array('id'=>$data['id']));

            if (!$result){
                $this->error('修改失败');
            }

            $this->success('修改成功');
        }
    }

    public function delete($id){
        $goodsModel = new GoodsModel();
        $result = $goodsModel->where(array('id'=>$id))->delete();
        if (!$result){
            $this->error('删除失败');
        }

        $this->success('删除成功');
    }
}